package org.javaboy.http_header_demo.config;

import org.apache.catalina.connector.Connector;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;

@Configuration
public class SecurityConfig {

    @Bean
    WebSecurityCustomizer webSecurityCustomizer() {
        return web -> web.ignoring().requestMatchers("/01.html");
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(a -> a.requestMatchers("/hello","/report").permitAll().anyRequest().authenticated())
                .requiresChannel(r->r
                        // http 接口必须通过 http 访问
                        .requestMatchers("/http").requiresInsecure()
                        // https 接口必须通过 https 访问
                        .requestMatchers("/https").requiresSecure())
//                .headers(h -> h.referrerPolicy(r->r.policy(ReferrerPolicyHeaderWriter.ReferrerPolicy.SAME_ORIGIN)).contentSecurityPolicy(c -> c.policyDirectives("Content-Security-Policy: default-src 'self';script-src 'self'; object-src 'none';style-src cdn.javaboy.org; img-src *; child-src https:;report-uri https://localhost:8080/report").reportOnly()))
                .formLogin(Customizer.withDefaults())
                .csrf(c -> c.disable());
        return http.build();
    }

    @Bean
    TomcatServletWebServerFactory tomcatServletWebServerFactory() {
        TomcatServletWebServerFactory factory =
                new TomcatServletWebServerFactory();
        factory.addAdditionalTomcatConnectors(createTomcatConnector());
        return factory;
    }
    private Connector createTomcatConnector() {
        Connector connector = new
                Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8080);
        return connector;
    }
}
